const app = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
import WeCropper from '../dist/we-cropper.js'
const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 100;
var times = 3,
  sw = wx.getSystemInfoSync().windowWidth;
Page({
  data: {
    canvasW: '',
    canvasH: '',
    maxlength: '',
    yululist: '',
    color: 'fff',
    type: '',
    imgid: '',
    pid: '',
    talk: '',
    name: '',
    lunboData: '',
    imgsshow: 'imgs',
    location: '',
    currentData: 0,
    tpsm: false,
    ylsm: false,
    image: 'https://pertailor.oss-cn-shenzhen.aliyuncs.com/2019-09-29/49e49b2f544b4e6d9e7a01f7b373686a.png',
    list: [{
        id: 1,
        name: '送家人'
      },
      {
        id: 2,
        name: '送朋友'
      },
      {
        id: 3,
        name: '告白'
      },
      {
        id: 4,
        name: '送老师'
      },
    ],
    cropperOpt: { //裁剪基础设置 
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 330
      }
    },
  },

  onLoad: function(options) { //购物车跳转修改
    qqmapsdk = new QQMapWX({
      key: 'HKWBZ-AX76O-QIUWP-SFHFY-B36TF-SLF24' //这里自己的key秘钥进行填充
    });
    console.log(options)
    if (options.type == 'car') {
      let json = JSON.parse(options.josn);
      console.log(json)
      //  this.getbgimg(json.pid)
      this.setData({
        type: options.type,
        talk: json.quotation,
        name: json.loan,
        location: json.position,
        color: json.tcolor == 0 ? 'fff' : 'bbb',
        sonid: json.sonid,
        pid: json.pid,
        image: json.url,
      })
    } else if (options.type == 'orderedit') { //订单跳转修改
      let orderitem = JSON.parse(options.orderitem);
      console.log(orderitem)
      this.setData({
        type: options.type,
        talk: orderitem.quotation,
        name: orderitem.loan,
        location: orderitem.position,
        image: orderitem.url,
        color: orderitem.tcolor == 0 ? 'fff' : 'bbb',
        sonid: orderitem.sonid,
        pid: orderitem.pid

      })
    } else if (options.type == 'company') { //企业定制
      this.setData({
        type: options.type,
        canvasW: sw * times,
        canvasH: (1080 / 1919) * sw * times,
        /*1080/1919背景图比例 */
      })

    } else if (options.type == 'companyedit') { //企业定制修改
      let companyitem = JSON.parse(options.companyitem);
      this.setData({
        type: options.type,
        talk: companyitem.quotation,
        name: companyitem.loan,
        location: companyitem.position,
        image: companyitem.pidurl,
        epid: companyitem.epid,
        color: companyitem.tcolor == 0 ? 'fff' : 'bbb',
        canvasW: sw * times,
        canvasH: (1080 / 1919) * sw * times,
        /*1080/1919背景图比例 */

      })
    } else { //私人订制跳转
      this.setData({
        talk: options.talk,
        name: options.name,
        location: options.location,
        color: options.color,
        image: options.imgurl
      })
    }
    this.getimgs();

    const { //裁剪
      cropperOpt
    } = this.data
    new WeCropper(cropperOpt)
      .on('ready', (ctx) => {})
      .on('beforeImageLoad', (ctx) => {
        console.log(`before picture loaded, i can do something`)
        console.log(`current canvas context:`, ctx)
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        console.log(`picture loaded`)
        console.log(`current canvas context:`, ctx)
        wx.hideToast()
      })
      .on('beforeDraw', (ctx, instance) => {
        console.log(`before canvas draw,i can do something`)
        console.log(`current canvas context:`, ctx)
      })
      .updateCanvas();

  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },
  getCropperImage() {
    var that = this;
    that.wecropper.getCropperImage((src) => {
      console.log(src)
      if (src) {
        //此处添加用户确定裁剪后执行的操作 src是截取到的图片路径
        console.log(src)
        that.setData({
          xx: false,
          img: src,
        })
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: app.globalData.url + '/jxb/goods/goods/uploadPic', //仅为示例，非真实的接口地址
          filePath: src,
          name: 'files',
          formData: {
            'user': 'test'
          },
          success(res) {
            let data = JSON.parse(res.data)
            console.log(data.data.pid)
            that.setData({
              image: data.data.url,
              pid: data.data.pid,
            })
            wx.hideLoading()
            //do something
          }
        })
      }
    })
  },
  getbgimg(pid) { //从购物车修改获取背景图片
    let _that = this;
    wx.request({ //传后台
      url: app.globalData.url + '/jxb/goods/goods/getBackground',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        pid: pid
      },
      success: function(res) {
        _that.setData({
          image: res.data.data[0].url
        });
      },

    })
  },
  getimgs() {
    if (wx.getStorageSync('bgimgs')) {
      let bgimgs = JSON.parse(wx.getStorageSync('bgimgs'));
      console.log(bgimgs)
      this.setData({
        lunboData: bgimgs
      });
      if (this.data.type == 'company') {
        this.setData({
          image: bgimgs[0].url
        });
      }
    }else{
    let _that = this;
    wx.request({ //传后台
      url: app.globalData.url + '/jxb/goods/goods/getBackground',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {},
      success: function(res) {
        if (_that.data.type == 'company') {
          _that.setData({
            image: res.data.data[0].url
          });
        }
        _that.setData({
          lunboData: res.data.data
        });
      },
    })
    } 
 },

  showimg: function(e) { //显示上传图片
    this.setData({
      imgsshow: 'imgs'
    });
  },
  showword: function() { //显示文字颜色
    this.setData({
      imgsshow: 'words'
    });
  },
  imgesxplain: function() { //参考语录
    this.setData({
      imgsshow: 'imgexplain',
    });
    this.getlist(1);
  },
  imgesxplainshow: function() { //显示图片说明
    this.setData({
      tpsm: true,
    });
  },
  closetpsm: function() { //关闭图片说明
    this.setData({
      tpsm: false,
    });
  },
  yuluxplainshow: function() { //显示语录说明
    this.setData({
      ylsm: true,
    });
  },
  closeylsm: function() { //关闭语录说明
    this.setData({
      ylsm: false,
    });
  },
  getlation: function () { //选择位置
  console.log(1)
    let that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.getLocal(latitude, longitude)
      }
    });

  },
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res);
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        let locationstr = city + '·' + district;
        console.log(locationstr)
        vm.setData({
          location: locationstr,
          border: 'none',
          background: 'rgba(255, 255, 255, .1)'
        });
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  openMap: function (e) {
    wx.authorize({
      scope: 'scope.userLocation',
      success: (res) => {

      },
    });
    var that = this
    wx.getSetting({
      success(res) {
        //这里判断是否有地位权限
        if (!res.authSetting['scope.userLocation']) {

          wx.showModal({
            title: '提示',
            content: '请求获取位置权限',
            success: function (res) {
              if (res.confirm == false) {

                return false;
              }
              wx.openSetting({
                success(res) {
                  //如果再次拒绝则返回页面并提示
                  if (!res.authSetting['scope.userLocation']) {
                    wx.showToast({
                      title: '请授权',
                      duration: 2000,
                      icon: 'none'
                    })
                  } else {
                    //允许授权，调用地图

                    that.getlation()
                  }
                }
              })
            }
          })
        } else {

          //如果有定位权限，调用地图
          that.getlation()
        }

      }

    })
  },
  save: function() { //提交
    this.setData({
      color: this.data.color
    });
    let that = this;
    if (this.data.location == '' || this.data.location == '·' || this.data.name == '' || this.data.talk == '' || this.data.talk.match(/^\s+$/) || this.data.name.match(/^\s+$/)) {
      let content = '';
      this.data.location == '' ? content = '亲，请选择位置' : this.data.location == '·' ? content = '亲，请选择位置' : this.data.name == '' ? content = '亲，请落款' : this.data.talk == '' ? content = '亲，请先填写或选择想说的话喔' : this.data.talk.match(/^\s+$/) ? content = '亲，请先填写或选择想说的话喔' : this.data.name.match(/^\s+$/) ? content = '亲，请填写落款喔' : '请完善信息'
      wx.showModal({
        title: '稍等一下',
        confirmText: '好的',
        confirmColor: '#28A8F9',
        showCancel: false,
        content: content,
        success: function(res) {
          if (res.confirm) {

          } else if (res.cancel) {
            return;
          }
        }
      })
    } else if (that.data.location !== '' && that.data.name !== '' && that.data.talk !== '') {
      if (this.data.type == 'car') { //从购物车修改跳转
        wx.navigateTo({
          url: '/pages/persondz/persondz?type=orderedit&fromwho=car' + '&imgid=' + that.data.imgid + '&image=' + that.data.image + '&location=' + that.data.location + '&name=' + that.data.name + '&talk=' + that.data.talk + '&color=' + that.data.color + '&sonid=' + that.data.sonid + '&pid=' + that.data.pid,
        })
      } else if (this.data.type == 'orderedit') { //从订单修改跳转
        wx.navigateTo({
          url: '/pages/persondz/persondz?type=orderedit&fromwho=order' + '&imgid=' + that.data.imgid + '&image=' + that.data.image + '&location=' + that.data.location + '&name=' + that.data.name + '&talk=' + that.data.talk + '&color=' + that.data.color + '&sonid=' + that.data.sonid + '&pid=' + that.data.pid,
        })
      } else if (this.data.type == 'company' || this.data.type == 'companyedit') { //企业定制
        that.canvascontent();

      } else if (this.data.type == 'companyedit') { //企业定制修改
        // that.canvascontent(); 
      } else { //从私人定制跳转
        console.log(that.data.pid)
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        prevPage.setData({
          talk: that.data.talk,
          name: that.data.name,
          location: that.data.location,
          image: that.data.image,
          pid: that.data.pid,
          color: that.data.color,
          border: 'none',
          border1: 'none',
          background1: 'rgba(255, 255, 255, .1)',
          background: 'rgba(255, 255, 255, .1)'

        })
        wx.navigateBack()
      }

    }
  },
  chooseimgs: function() { //从本地获取图片
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(res)
        that.setData({
          cutImage: 'show',
          addtribeConShow: 'hide',
          xx: true
        });
        that.wecropper.pushOrign(res.tempFilePaths[0]);
      }
    })
  },
  // getstr() {
  //   if (this.data.flage == true) {
  //     let le = this.data.le;
  //     this.setData({
  //       talk: this.data.talk.substr(0, le)
  //     })
  //     wx.showToast({
  //       title: '格式已调整',
  //       duration: 2000,
  //       icon: 'none'
  //     })
  //   }
  // },
  getstr() {

    // this.setData({
    //   bgtalk: this.data.talk.replace(/[\r\n]/g, "")
    // })
    // if (this.data.flage == true) {
    //   let le = this.data.le;
    //   console.log(le)
    //   this.setData({
    //     talk: this.data.talk.substr(0, le)
    //   })
    //   wx.showToast({
    //     title: '最多输入36个字符或5行',
    //     duration: 2000,
    //     icon: 'none'
    //   })
    // }
  },
  talkinp(e) { //获取说的话
    // const query = wx.createSelectorQuery()
    // query.select('.talk').boundingClientRect()
    // query.selectViewport().scrollOffset()
    // let that = this
    // query.exec(function(res) {
    //   res[0].top // #the-id节点的上边界坐标
    //   res[1].scrollTop // 显示区域的竖直滚动位置
    //   // console.log('打印demo的元素的信息', res);
    //   console.log('打印高度', res[0].height);
    //   if (res[0].height == 136) {
    //     console.log(res[0])
    //     // wx.showToast({
    //     //   title: '最多输入36个字符或5行1',
    //     //   duration: 2000,
    //     //   icon: 'none'
    //     // })
    //     that.setData({
    //       le: res[0].dataset.itrm.length,
    //       flage: true,
    //       //  maxlength: parseInt(e.detail.value.length),
    //       talk: e.detail.value,
    //       // gbtalk: (e.detail.val).replace(/\ +/g, ""),
    //     })
    //   } else if (res[0].height < 136) {
    //     that.setData({
    //       flage: false,
    //     })
    //   }
    // })

    let n = (e.detail.value.split('\n')).length - 1
    if (parseInt(e.detail.value.length) >= 30 || n >= 5) {
      // this.setData({
      //   maxlength: parseInt(e.detail.value.length)
      // })
      wx.showToast({
        title: '最多输入30个字符或5行',
        duration: 2000,
        icon: 'none'
      })
    } 
      this.setData({
        talk: e.detail.value,
        bgtalk: e.detail.value,
        // maxlength: '',
      })
   
  },
  nameinp(e) { //获取姓名
    if (parseInt(e.detail.value.length) >= 5) {
      wx.showToast({
        title: '最多输入5个字符',
        duration: 2000,
        icon: 'none'
      })
    }
    this.setData({
      name: e.detail.value
    })
  },
  inputFocus() { //落款获取焦点
    this.setData({
      border1: '1px solid #fff'
    })
  },
  inputBlur() { //落款失去焦点
    this.setData({
      border1: 'none',
      background1: 'rgba(255, 255, 255, .1)'
    })
  },

  bindchange: function(e) { //切换语录
    const that = this;
    that.setData({
      currentData: e.detail.current
    })
  },
  //点击切换，滑块index赋值
  getlist(type) {
    let that = this;
    wx.request({ //传后台
      url: app.globalData.url + '/jxb/goods/goods/getQuotation',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        type: type
      },
      success: function(res) {
        that.setData({
          yululist: res.data.data
        });

      },

    })
  },
  checkCurrent: function(e) {
    let that = this;
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })

    }
  },
  changeimg(e) { //更换图片
    let url = e.currentTarget.dataset.url;
    this.setData({
      image: url.url,
      pid: url.pid
    })
  },
  colorwitht() { //切换颜色 白色
    this.setData({
      color: 'fff'
    })
  },
  colorblue() { //切换颜色 蓝色
    this.setData({
      color: 'bbb'
    })
  },
  checkCurrent: function(e) { //切换语录
    const that = this;
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })

      let type = Number(e.target.dataset.current)+1 

      that.getlist(type)

    }
  },
  chooseyulu(e) {
    this.setData({
      talk: e.target.dataset.quotation
    })
  },

  canvascontent: function() { //生成图片
    wx.showLoading({
      title: '正在生成图片...',
      mask: true,
    })
    var height = 0;
    var color = '';
    this.data.color == 'fff' ? color = "#fff" : color = '#29A6F8';
    var that = this;
    const ctx = wx.createCanvasContext('demo');
    ctx.font = 'normal normal 12px 微软雅黑';
    ctx.setFontSize(toPx(18));
    ctx.setTextBaseline('top');
    ctx.setTextAlign('left');
    //  画背景图（网络图片需要先下载）  
    let p1 = new Promise((resolve, reject) => {
      wx.downloadFile({
        url: 'https://pertailor.oss-cn-shenzhen.aliyuncs.com/2019-09-02/c67e6b4dcefd4ada9e7bdf549b620f6c.png',
        success: res => {
          if (res.statusCode == 200) {
            var img = res.tempFilePath;
            resolve(img)
            console.log(img)
            ctx.drawImage(img, 0, 0, this.data.canvasW, this.data.canvasH)
          }
        }

      });
    });
    let p2 = new Promise((resolve, reject) => {
      let that = this;
      wx.downloadFile({
        url: that.data.image,
        success: res => {
          if (res.statusCode == 200) {
            var img = res.tempFilePath;
            resolve(img)
            console.log(img)
            ctx.drawImage(img, toPx(545), toPx(206), toPx(192), toPx(204))
            ctx.drawImage(img, toPx(324), toPx(336), toPx(49), toPx(49))
          }
        }

      });
    });
    //画图
    Promise.all([p1, p2]).then((result) => {
      var param = {
        str: that.data.talk,
        ctx: ctx,
        ellipsis: true,
        len: 178
      }
      var param1 = {
        str: (that.data.talk).replace(/[\r\n]/g, "").replace(/\ +/g, ""),
        ctx: ctx,
        ellipsis: true,
        len: 178
      }
      var len1 = fillLinesText(param1).length;
      var len = fillLinesText(param).length;
      ctx.setTextAlign('left');
      for (var i = 0; i < len1; i++) { //背面的字
        ctx.setFillStyle('#29A6F8');
        ctx.fillText(fillLinesText(param1)[i], toPx(328), toPx(216 + 24 * i));
      }
      ctx.setTextAlign('left');
      for (var i = 0; i < len; i++) { //正面的字
        ctx.setFillStyle(color);
        ctx.fillText(fillLinesText(param)[i], toPx(556), toPx(216 + 24 * i));
      }

      // 落款
      ctx.setFontSize(toPx(10));
      ctx.setTextAlign('right');
      ctx.setFillStyle(color);
      ctx.fillText('【' + that.data.name + '】', toPx(724), toPx(360));
      ctx.setFillStyle('#29A6F8');
      ctx.fillText('【' + that.data.name + '】', toPx(490), toPx(290));
      // 定位
      ctx.setTextAlign('right');
      ctx.setFillStyle(color);
      ctx.fillText(that.data.location, toPx(724), toPx(380));
      ctx.setFillStyle('#29A6F8');
      ctx.fillText(that.data.location, toPx(490), toPx(310));
      ctx.draw(true, () => {
          setTimeout(function () {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              destWidth: that.data.canvasW, //画布宽高*dpr 以iphone6为准
              destHeight: that.data.canvasH,
              canvasId: 'demo',
              success: function (res) {
                console.log(res.tempFilePath)
                that.changehead(res.tempFilePath); //上传效果图 

              }
            })
          },100)

      });
    }).catch((error) => {
      console.log(error) // 失败了，打出 '失败'
    })

  },
  changehead(path) { //上传效果图
    let that = this;
    wx.uploadFile({
      url: app.globalData.url + '/jxb/login/login/uploadAvatar', //仅为示例，非真实的接口地址
      filePath: path,
      name: 'files',
      formData: {
        'user': 'test'
      },
      success(res) {
        wx.hideLoading()
        let data = JSON.parse(res.data);
        if (that.data.type == 'companyedit') {
          that.companyedit(data.data.url)
        } else if (that.data.type == 'company') {
          that.companyadd(data.data.url) //保存企业定制
        }

      }
    })
  },

  companyadd(pidiurl) { //企业定制上传图文
    let _that = this;
    wx.request({ //传后台
      url: app.globalData.url + '/jxb/egoods/egoods/addPicText',
      method: 'get',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        customer: wx.getStorageSync('customer'),
        pidurl: this.data.image,
        pidiurl: pidiurl,
        loan: this.data.name,
        quotation: this.data.talk,
        position: this.data.location,
        tcolor: this.data.color == 'fff' ? 0 : 1,
      },
      success: function(res) {
        console.log(res)
        wx.navigateBack();

        return;
      },

    })
  },
  companyedit(pidiurl) { //企业定制修改
    let _that = this;
    wx.request({ //传后台
      url: app.globalData.url + '/jxb/eorder/updateEOrder',
      method: 'get',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        token: wx.getStorageSync('token'),
        epid: this.data.epid,
        pidurl: this.data.image,
        pidiurl: pidiurl,
        loan: this.data.name,
        quotation: this.data.talk,
        position: this.data.location,
        tcolor: this.data.color == 'fff' ? 0 : 1,
      },
      success: function(res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '修改成功',
          })
          wx.navigateBack()
        }

      },

    })
  },

})

function fillLinesText(param) {
  var str = "",
    brr = [],
    arr = param.str.split("");
  if (!param.line) param.line = 999

  for (var j = 0; j < param.line; j++) {

    var wrap = false;
    if (arr.length) {
      for (var i = 0; i < arr.length; i++) {
        str += arr[i];
        if (arr[i].match(/[\r\n]/g)) {
          wrap = true;
          brr.push(str.substring(0, str.length - 1))
          arr = arr.slice(str.length - 1);
          arr.splice(0, 1);
          str = "";
          break;
        }
        const metrics = param.ctx.measureText(str);
        if (metrics.width > toPx(param.len)) {
          wrap = true;
          if (j == param.line - 1 && param.ellipsis) {
            brr.push(str.substring(0, str.length - 2) + '…')
          } else {
            brr.push(str.substring(0, str.length - 1));
          }
          arr = arr.slice(str.length - 1);
          str = "";
          break;
        }
      }
      if (wrap == false) {
        brr.push(str);
        arr = [];
      }
    }

  }
  return brr
}
var toPx = (l) => {
  return Math.ceil(l / (750 / sw)) * times;
}